package db

import (
	"ai/internal/db/models"
	"ai/internal/logging"
	"path/filepath"

	"github.com/toolkits/pkg/file"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func InitDB() *gorm.DB {
	dbFile := filepath.Join(file.SelfDir(), "ai.db")
	db, err := gorm.Open(sqlite.Open(dbFile), &gorm.Config{})
	if err != nil {
		logging.Error("Failed to connect database:", err)
	}

	// Migrate the schema
	err = db.AutoMigrate(&models.User{}, &models.Question{}, &models.Answer{}, &models.Activity{}, &models.WrongSet{}, &models.UserQuestionStatus{})
	if err != nil {
		logging.Error("Failed to migrate database:", err)
	}

	// Check and add default users
	checkAndAddDefaultUsers(db)

	logging.Info("Database connected and migrated successfully")
	return db
}

func checkAndAddDefaultUsers(db *gorm.DB) {
	defaultUsers := []models.User{
		{Username: "admin", Password: "admin123", Role: "admin"},
		{Username: "user", Password: "user123", Role: "user"},
	}

	for _, user := range defaultUsers {
		var existingUser models.User
		if err := db.Where("username = ?", user.Username).First(&existingUser).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				if err := db.Create(&user).Error; err != nil {
					logging.Error("Failed to create default user:", user.Username, err)
				} else {
					logging.Info("Default user created:", user.Username)
				}
			} else {
				logging.Error("Error checking user:", user.Username, err)
			}
		}
	}
}
